package cz.schovjan.proj.controllers;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import cz.schovjan.proj.dto.Member;
import cz.schovjan.proj.service.IMember;

/**
 * Kontroler pro editaci/detail clena.
 * @author schovjan
 *
 */
@Controller
@RequestMapping("/member")
@SessionAttributes({"band","user"}) //user se musi uvest taky, jinak se nepouzije
public class MemberController extends Base {

	/** stranka s detailem clena */
	private static final String MEMBER_DETAIL = "detailMember";	
		
	/** Service pro cleny.	 */
	@Autowired
	private IMember members;
	
	
	/////////////////
	//OBSLUZNE FUKNCE ------------------------------------------------------------
	/////////////////
	
	
	/**
	 * Zobrazi detail clena.
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/detail")
	public String detail(@RequestParam("id") int id, ModelMap model) {
		Member m = members.find(id);
		model.addAttribute("member", m);
		model.addAttribute("edit", false);
		
		return MEMBER_DETAIL;
	}
	
	
	/**
	 * Zobrazi detail clena.
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/edit")
	public String edit(@RequestParam("id") int id, ModelMap model) {
		model.addAttribute("member", members.find(id));
		model.addAttribute("edit", true);
		
		return MEMBER_DETAIL;
	}
	
	
	/**
	 * Ulozeni zmeny pri editaci clena.
	 * @param member
	 * @param result
	 * @param model
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST, value="/memberSave")
	public String memberSave(@Valid @ModelAttribute("member") Member member, BindingResult result, ModelMap model) {
		model.addAttribute("edit", true);
		
		if (member.getNick().isEmpty() && member.getName().isEmpty() && member.getSurname().isEmpty()) {
			result.addError(new ObjectError("clenBezJmena", MSG_VALID_MEMBER));
		}
		
		if (result.hasErrors()) {
			return MEMBER_DETAIL;
		}
		members.save(member.getId(),
						member.getNick(),
						member.getName(),
						member.getSurname(),
						member.getEmail(),
						member.getPhone(),
						member.getDateOfBirth(),
						member.getJob());
		model.addAttribute("message", MSG_MEMBER_SAVE);
		model.addAttribute("member", members.find(member.getId()));
				
		return MEMBER_DETAIL;
	}
	
}
